package com.ruoyi.plus.utils;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.ip.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springMvc拦截器
 *
 * @author likun
 * @date 2020-1-12
 */
@Component
public class UrlInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //如果是OPTIONS的请求，不用打印日志
            if (RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
                return super.preHandle(request, response, handler);
            }

            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                if (handlerMethod.getBean() instanceof BasicErrorController) {
                    BasicErrorController errorController = (BasicErrorController) ((HandlerMethod) handler).getBean();
                    LOGGER.error("{}\n", errorController.error(request).toString());
                } else {
                    LOGGER.debug("{} {} {} Handler:{} Params:{}",
                            IpUtils.getIpAddr(request), request.getMethod(), request.getRequestURL(),
                            handlerMethod.getMethod(),
                            JSON.toJSON(request.getParameterMap()));
                }
            } else {
                LOGGER.trace("{} {} {}",
                        IpUtils.getIpAddr(request), request.getMethod(), request.getRequestURL());
            }
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            LOGGER.error("请求拦截异常：{}", e);
        }
        return true;
    }

}